package com.chookss.mine.set;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.base.Token;
import com.chookss.login.LoginActivity;
import com.chookss.mine.entity.AccountEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.RSACoder;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.UUidUtils;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.old.SignUtils;
import com.chookss.view.InitDialog;
import com.chookss.view.listener.ShareDialogListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.Nullable;

public class AccountActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_txt)
    TextView commonRightTxt;
    @BindView(R.id.tvInit)
    TextView tvInit;
    @BindView(R.id.llAdd)
    LinearLayout llAdd;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private MyAccountAdapter adapter;
    private List<AccountEntity> list = new ArrayList<>();
    private String ANDROID_ID = "";
    private boolean isManager = false;//是否处于管理状态

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_my_account);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        commonTitleTxt.setText("切换所属组织");
        commonRightTxt.setVisibility(View.VISIBLE);
        commonRightTxt.setText("管理");
        List<AccountEntity> oldList = XJson.getAccountsList(AccountActivity.this, new ShareUtils().getString(AccountActivity.this, StaticClass.APPACCOUNT, ""), AccountEntity.class);
        if (oldList.size() == 0) {
            AccountEntity accountEntity = new AccountEntity();
            accountEntity.setCompanyName(new ShareUtils().getString(AccountActivity.this, StaticClass.COMPANYNAME, ""));
            accountEntity.setCompanyCode(new ShareUtils().getString(AccountActivity.this, StaticClass.COMPANYCODE, ""));
            accountEntity.setEmployeeCode(new ShareUtils().getString(AccountActivity.this, StaticClass.EMPLOYEECODE, ""));
            accountEntity.setHeadPhotoThumbUrl(new ShareUtils().getString(AccountActivity.this, StaticClass.USER_AVATAR_URL, ""));
            accountEntity.setNickName(new ShareUtils().getString(AccountActivity.this, StaticClass.USER_NICKNAME, ""));
            accountEntity.setPassword(new ShareUtils().getString(AccountActivity.this, StaticClass.ORIGINALPASS, ""));
            accountEntity.setPhone(new ShareUtils().getString(AccountActivity.this, StaticClass.APPACCOUNT, ""));
            list.add(accountEntity);
            XJson.setAccountsList(AccountActivity.this, new ShareUtils().getString(AccountActivity.this, StaticClass.APPACCOUNT, ""), list);
        } else {
            list.addAll(oldList);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new MyAccountAdapter(R.layout.item_my_account, this, list);
        recyclerView.setAdapter(adapter);

        if (!"13300000000".equals(new ShareUtils().getString(AccountActivity.this, StaticClass.USERNAME, ""))) {
            getUUID();
        }
    }

    @OnClick({R.id.common_title_back, R.id.common_right_txt, R.id.llAdd})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
                if(commonTitleTxt==null){
                    return;
                }
                if (isManager) {
                    isManager = false;
                    commonTitleTxt.setText("切换所属组织");
                    tvInit.setText("点击切换所属组织");
                    commonRightTxt.setText("管理");
                    llAdd.setVisibility(View.VISIBLE);
                } else {
                    isManager = true;
                    commonTitleTxt.setText("管理组织");
                    tvInit.setText("清除组织登录记录");
                    commonRightTxt.setText("返回");
                    llAdd.setVisibility(View.GONE);
                }
                adapter.notifyDataSetChanged();
                break;
            case R.id.llAdd:
                Intent intent = new Intent(this, LoginActivity.class);
                intent.putExtra("isAdd", true);
                startActivity(intent);
                break;
        }
    }

    class MyAccountAdapter extends BaseQuickAdapter<AccountEntity, BaseViewHolderEx> {
        private Context context;

        public MyAccountAdapter(int layoutResId, Context context, @Nullable List<AccountEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, AccountEntity item) {

            ImageView ivHead = helper.getView(R.id.ivHead);
            TextView tvCompany = helper.getView(R.id.tvCompany);
            TextView tvCurrent = helper.getView(R.id.tvCurrent);
            TextView tvClear = helper.getView(R.id.tvClear);
            String itemPhone = item.getPhone();
            if (Utils.isNull(itemPhone)) {
                tvCompany.setText(item.getCompanyName());
            } else {
                if (itemPhone.length() > 4) {
                    tvCompany.setText(item.getCompanyName() + " (尾号" + itemPhone.substring(itemPhone.length() - 4, itemPhone.length())+")");
                } else {
                    tvCompany.setText(item.getCompanyName());
                }
            }
            if (item.getCompanyName().equals(new ShareUtils().getString(AccountActivity.this, StaticClass.COMPANYNAME, ""))&&item.getPhone().equals(new ShareUtils().getString(AccountActivity.this, StaticClass.APPACCOUNT, ""))) {
                tvCurrent.setVisibility(View.VISIBLE);
            } else {
                tvCurrent.setVisibility(View.GONE);
            }
            if (isManager) {
                tvClear.setVisibility(View.VISIBLE);
            } else {
                tvClear.setVisibility(View.GONE);
            }
            GlideUtils.loadCustomRound(AccountActivity.this, item.getHeadPhotoThumbUrl(), ivHead, R.drawable.default_user_head, 3);
//            String tag = (String) ivHead.getTag(R.id.ivHead);
//            if (!item.getHeadPhotoThumbUrl().equals(tag)) {
//                // 加载图片
//                  ivHead.setTag(R.id.ivHead, item.getHeadPhotoThumbUrl());
//            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if (!isManager) {
                        if (tvCurrent.getVisibility() == View.VISIBLE) {
                            MyToast.show("当前账户已登录");
                        } else if (!Utils.isNull(item.getPassword())) {
                            if(MyApp.uploadLogStatus||MyApp.uploadRecordStatus||MyApp.uploadHolidayStatus){
                                new InitDialog(AccountActivity.this,
                                        "提示", "文件正在上传中，切换账号将会中止上传操作，确定中止么？", "确定", true,
                                        new ShareDialogListener() {
                                            @Override
                                            public void onClick() {
                                                EventBus.getDefault().post(new MyEvent("Stop_File_Upload"));
                                                unbindPUSHID(item, Token.INSTANCE.getToken());
                                            }
                                        }).show();
                            }else{
                                unbindPUSHID(item, Token.INSTANCE.getToken());
                            }

                        } else {
                            MyToast.show("请通过密码重新登录");
                            //当之前是验证码登录时，切换账号需要重新密码登录，账号信息传过去
                            Intent intent = new Intent(AccountActivity.this, LoginActivity.class);
                            intent.putExtra("isAdd", true);
                            intent.putExtra("company",item.getCompanyName());
                            intent.putExtra("phone",item.getPhone());
                            startActivity(intent);
                        }
                    }

                }
            });
            tvClear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    new AlertDialog.Builder(AccountActivity.this)
                            .setTitle("提示")
                            .setMessage("确认要清除" + item.getCompanyName() + "账户信息么？")
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    list.remove(helper.getItemPosition());
                                    adapter.notifyDataSetChanged();
                                    XJson.setAccountsList(AccountActivity.this, new ShareUtils().getString(AccountActivity.this, StaticClass.APPACCOUNT, ""), list);
                                    if (tvCurrent.getVisibility() == View.VISIBLE) {
                                        quit("");
                                    }
                                }
                            }).setNegativeButton("取消", null).show();

                }
            });
        }
    }

    public void unbindPUSHID(AccountEntity accountEntity, String token) {
        //解绑设备id
        Map<String, String> map = new HashMap<>();
        map.put("employeeCode", accountEntity.getEmployeeCode());
        map.put("companyCode", accountEntity.getCompanyCode());
        showLoading();
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.unbindPUSHID, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                JSONObject reObject = null;
                try {
                    reObject = new JSONObject(data);
                    if ("200".equals(reObject.getString("code"))) {
                        login(accountEntity,token);
                    } else {
                        dismissLoading();
                        MyToast.show(reObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    dismissLoading();
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(errorMsg);
            }
        });
    }

    public void login(AccountEntity accountEntity, String token) {
        String deviceName = Build.BRAND + " " + Build.MODEL;
//        if (tvPassword.getText().toString().length() < 8) {
//            MyToast.show("密码不能少于8位");
//        }
        if (accountEntity.getPhone().equals("13300000000")||accountEntity.getPhone().equals("13503825592")) {
            ANDROID_ID = "27f6fd2ba9cfffff";
        }
        if (accountEntity.getPhone().equals("13503825591")) {
            ANDROID_ID = "27f6fd2ba9c9521f";
        }
        if (accountEntity.getPhone().equals("15713883582")) {
            ANDROID_ID = "27f6fd2ba9c9eee";
        }
        String encodePassword = RSACoder.encryRas(accountEntity.getPassword());
        String encodeUsername = RSACoder.encryRas(accountEntity.getPhone());
        String encodeDevice = RSACoder.encryRas(ANDROID_ID);
        Map<String, Object> map = new HashMap<>();
        map.put("companyName", accountEntity.getCompanyName());
        map.put("username", accountEntity.getPhone());
        map.put("password", accountEntity.getPassword());
        map.put("type", "1");
        map.put("device", ANDROID_ID);
        map.put("deviceName", deviceName);
        String timeStamp = SignUtils.getTimeStamp();//20201208125238
        String nonce = SignUtils.getRandomString(14);
        String makeSignStr = SignUtils.makeSignStr(map, timeStamp, nonce, true);
        Map<String, String> maps = new HashMap<>();
        maps.put("companyName", accountEntity.getCompanyName());
        maps.put("username", encodeUsername);
        maps.put("password", encodePassword);
        maps.put("type", "1");
        maps.put("device", encodeDevice);
        maps.put("deviceName", deviceName);
        maps.put("timestamp", timeStamp);
        maps.put("nonce", nonce);
        maps.put("sign", makeSignStr);
//        OkGoConfig.init(MyApp.appCtx, "login",
//                Utils.getVersionName(AccountActivity.this));
        MyHttpRequest.postRequest(Urls.login, this, maps, new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response.body().toString());
                    dismissLoading();
                    if ("200".equals(jsonObject.getString("code"))) {
                        //记录用户名、原始密码
                        new ShareUtils().putString(AccountActivity.this, StaticClass.USERNAME, accountEntity.getPhone());
                        new ShareUtils().putString(AccountActivity.this, StaticClass.ORIGINALPASS, accountEntity.getPassword());
                        quit(token);
                        JSONObject data = jsonObject.getJSONObject("data");
                        NavigationTools.saveUserData(AccountActivity.this,data,"","");
                        if (data.getBoolean("flag")) {
                            MyToast.show("首次登录，建议您重新设置密码");
                            Intent intent = new Intent(AccountActivity.this, ChangePassActivity.class);
                            intent.putExtra("type", "login");
                            startActivity(intent);
                            finish();
                        } else {
//                            EventBus.getDefault().post(new MyEvent("refreshAccount"));
                            NavigationTools.toChangeHome(AccountActivity.this);
                            finish();
                        }
                    } else {
                        MyToast.show(jsonObject.getString("msg"));
                        //解绑成功  登录失败  所以要重新去绑定一下
                        checkLogin();
                    }

                } catch (JSONException e) {
                    dismissLoading();
                    e.printStackTrace();
                }
            }
        });
    }

    private void quit(String token) {
        Map<String, String> map = new HashMap<>();
        if (!Utils.isNull(token)) {
            map.put("logoutToken", token);
        }
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.logout, SignUtils2.makeSignStr(map), false,
                new ObserverCallback<String>() {
                    @Override
                    public void onSuccess(String data) throws Exception {
                        if (Utils.isNull(token)) {
                            JSONObject reObject = new JSONObject(data);
                            if ("200".equals(reObject.getString("code"))) {
                                startActivity(new Intent(AccountActivity.this, LoginActivity.class));
                                finish();
                            } else {
                                MyToast.show(reObject.getString("msg"));
                            }
                        }
                    }

                    @Override
                    public void onError(String errorMsg) {
                        MyToast.show(Utils.onErrorTips(errorMsg));
                    }
                });
    }
    public void checkLogin() {
        //绑定推送
        Map<String, String> map = new HashMap<>();
        String pushId = MyApp.PUSHID;
        if (Utils.isNull(pushId)) {
            pushId = new ShareUtils().getString(this, StaticClass.PUSHID, "");
        }
        map.put("alibabaUid", pushId);
        map.put("systemType", "1");
        MyHttpRequest.getRequest(Urls.checkLogin, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
            }
        });
    }
    private void getUUID() {
        ANDROID_ID = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
//        测试
//         ANDROID_ID = "27f6fd2ba9c9521f";
//         ANDROID_ID = "27f6fd2ba9c952ff";   //157小号
        if(XXPermissions.isGranted(this,Permission.Group.STORAGE)){
            ANDROID_ID = UUidUtils.getCustomUUID(AccountActivity.this, ANDROID_ID);
        }else{
            if(Utils.isNull(ANDROID_ID)){
                String id= new ShareUtils().getString(this, "local_id", "");
                if (Utils.isNull(id)) {
                    String uuid= UUID.randomUUID().toString();
                    ANDROID_ID=uuid;
                    new ShareUtils().putString(this, "local_id", uuid);
                }else{
                    ANDROID_ID=id;
                }
            }
        }
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            ANDROID_ID = UUidUtils.getCustomUUID(AccountActivity.this, ANDROID_ID);
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                    }
                });
    }

}
